import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class DateTimePicker extends StatefulWidget {
  final DateTime initialDate;
  final Function(DateTime) onDateSelected;
  final DateTime? firstDate;
  final DateTime? lastDate;
  
  const DateTimePicker({
    super.key,
    required this.initialDate,
    required this.onDateSelected,
    this.firstDate,
    this.lastDate,
  });
  
  @override
  State<DateTimePicker> createState() => _DateTimePickerState();
}

class _DateTimePickerState extends State<DateTimePicker> {
  late DateTime _selectedDate;
  
  @override
  void initState() {
    super.initState();
    _selectedDate = widget.initialDate;
  }
  
  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: widget.firstDate ?? DateTime(2020),
      lastDate: widget.lastDate ?? DateTime.now().add(const Duration(days: 365)),
      // 设置中文本地化
      locale: const Locale('zh', 'CN'),
      builder: (BuildContext context, Widget? child) {
        return Localizations.override(
          context: context,
          locale: const Locale('zh', 'CN'),
          child: Theme(
            data: ThemeData.light().copyWith(
              colorScheme: const ColorScheme.light(
                primary: Colors.blue,
                onPrimary: Colors.white,
              ),
              // 设置日期选择器文本样式
              textTheme: const TextTheme(
                bodyMedium: TextStyle(fontFamily: ''),
              ),
            ),
            child: child!,
          ),
        );
      },
    );
    
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
      widget.onDateSelected(picked);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: const Icon(Icons.calendar_today, color: Colors.blue),
      title: const Text(
        '账单时间',
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text(
        DateFormat('yyyy年MM月dd日').format(_selectedDate),
        style: const TextStyle(fontSize: 16),
      ),
      trailing: const Icon(Icons.arrow_drop_down, color: Colors.grey),
      onTap: _selectDate,
      contentPadding: const EdgeInsets.symmetric(horizontal: 8),
    );
  }
}